<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of AttachmentService
 *
 * @author Administrator
 */

namespace frontend\service\upload;

use Qiniu\Auth;
use frontend\bean\Attachment;
use frontend\dao\AttachmentDao;
use frontend\library\MT;
use Yii;

class UploadService {

    private $attachDao;

    //put your code here
    public function __construct(AttachmentDao $attachDao) {
        $this->attachDao = $attachDao;
    }

    public function verifyCallback() {
          $authstr = $_SERVER['HTTP_AUTHORIZATION'];
        if (strpos($authstr, "QBox ") != 0) {
            return false;
        }
        $auth = explode(":", substr($authstr, 5));
        if (sizeof($auth) != 2 || $auth[0] != C('accessKey')) {
            return false;
        }
        $data = "/callback.php\n" . file_get_contents('php://input');
        return URLSafeBase64Encode(hash_hmac('sha1', $data, C("secretKey"), true)) == $auth[1];
    }

    /*
     * @return string $upToken
     */

    public function getUploadToken() {
        $bucket = Yii::$app->params['qiniu']['bucket'];
        $accessKey = Yii::$app->params['qiniu']['access_key']; //Config::ACCESS_KEY;
        $secretKey = Yii::$app->params['qiniu']['secret_key'];
        ;
        $auth = new Auth($accessKey, $secretKey);
        $policy = array(
            'callbackUrl' => 'http://simonlu9.xicp.net/yii-advanced/frontend/web/api/upload/callback',
            'callbackBody' => '{"fname":"$(fname)","size": $(fsize), "fkey":"$(key)", "desc":"$(x:desc)", "uid":' . 1 . '}'
        );

        return $upToken = $auth->uploadToken($bucket, null, 3600, $policy);
    }

    public function addAttachment(Attachment $attach) {
        $attach->setCreate_time(MT::getTime());
        $attach->setType(1);
        $res = $this->attachDao->addAttachment($attach);

        return $this->attachDao->getNewId();
    }
    
    
    public function getAttachmentInfo($aid){
        return $this->attachDao->getAttachmentInfo($aid);
    }

}
